<template>
  <div>
    <div class="workDynamic">
      <CaseTitle :position="fromPath" :subtitle="content.typeName" />

      <div class="dynamicInner">
        <div class="dynamicInfo">
          <div class="dynamicTitle">
            {{ content.noticeTitle }}
          </div>
          <div class="dynamicBrief">
            <div class="briefBox">发布时间：{{ content.pushTime!==null?(content.pushTime.slice(0,10)+' '+content.pushTime.slice(11,19)):'' }}</div>
<!--            <div class="briefBox">作者：{{ content.name }}</div>-->
            <div class="briefBox">来源：{{ content.source }}</div>
          </div>

          <div class="dynamicContent ql-editor content-detail">
            <!--            <div v-html="content.noticeText" />-->
          </div>
          <div v-if="(content.attachmentUrl!==null)&&(content.attachmentName!==null)&&(content.attachmentId!==null)" class="attachment">
            <div class="word">附件：</div>
            <div class="attachmentName">
              <el-link
                id="el-link"
                type="primary"
                style="display:inline-block"
                :underline="false"
                @click="getHref(content.attachmentUrl,content.attachmentName)"
              >
                {{ content.attachmentName }}
              </el-link>
              <el-button
                id="el-button"
                type="text"
                style="display:inline-block;color: #85ce61"
                icon="el-icon-view"
                @click="previewFile(content)"
              >
                预览</el-button>
              <!-- 点击上面的预览按钮会弹出文件预览框 -->

              <!-- 预览 -->
              <el-dialog
                title="预览"
                :append-to-body="true"
                :lock-scroll="false"
                :visible.sync="dialog.dialogVisible"
              >
                <div v-if="dialog.isPdf" v-loading="loading" class="pdfClass">
                  <vue-office-pdf :src="dialog.src" />
                </div>
                <!-- <div v-else-if="dialog.isExcel" class="excelClass" v-html="excelHtml" /> -->
                <div v-else-if="dialog.isExcel">
                  <el-table
                    :data="excelData"
                    border
                    stripe
                    :header-cell-style="{'background':'#F5F4F7'}"
                  >
                    <el-table-column
                      type="index"
                      label="序号"
                      width="60"
                      :resizable="false"
                      align="center"
                    />
                    <el-table-column
                      v-for="(value, key, index) in excelData[0]"
                      :key="index"
                      :prop="key"
                      :label="key"
                    />
                  </el-table>
                </div>
<!--                <div v-else-if="dialog.isWord" class="wordClass" v-html="wordHtml" />-->
                <div v-else-if="dialog.isWord" style="overflow-y: auto">
                  <vue-office-docx
                    :src="dialog.src"
                    style="height: 100vh;"
                  />
                </div>
                <div v-else class="imgfile">
                  <el-image
                    :src="dialog.src"
                    alt=""
                    fit="cover"
                  ></el-image>
                </div>
              </el-dialog>
            </div>
          </div>
          <div class="dynamicFooter">
            <!--     上下条       -->
            <div v-if="!$route.query.type" class="pageJump">
              <div :class="[up ? 'dynamicHref1' : 'dynamicHref2']">
                <el-link
                  :underline="false"
                  :disabled="!up"
                  @click="getBefore"
                >上一条：{{ up ? up.noticeTitle : "已是最新" }}</el-link>
              </div>
              <div :class="[down ? 'dynamicHref1' : 'dynamicHref2']">
                <el-link
                  :underline="false"
                  :disabled="!down"
                  @click="getAfter"
                >下一条：{{ down ? down.noticeTitle : "已是最后" }}</el-link>
              </div>
              <div v-if="isShow" class="pageJump-right" @click="returnList">返回<br>列表</div>
            </div>
            <!--   按钮         -->
            <div v-if="$route.query.type" class="subBtn">
              <el-button
                v-if="content.status === 0"
                type="primary"
                @click="editBack"
              >编辑</el-button>
              <el-button
                v-if="content.status === 0"
                v-permission="'contentAudit:edit'"
                type="danger"
                @click="preToSubmit"
              >提交</el-button>
              <el-button type="primary" @click="listBack">返回列表</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CaseTitle from '@/components/common/CaseTitle';
import { GetContentNoticeBYyId, getContentUpDown } from '@/api/contentnotice';
import { PublishContentNotice } from '@/api/submit';
import { attachmentDownload } from '@/api/attachment'
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import * as XLSX from 'xlsx';
// import mammoth from 'mammoth';
import VueOfficePdf from '@vue-office/pdf';
import VueOfficeDocx from '@vue-office/docx';
import '@vue-office/docx/lib/index.css'
// import * as vm from 'vm';
export default {
  name: 'WorkDynamic',
  components: {
    CaseTitle,
    VueOfficePdf,
    VueOfficeDocx
  },
  data() {
    return {
      // 状态
      id: '',
      idArr: [],
      fromPath: '',
      fromTitle: '',
      up: {},
      down: {},
      content: {
        pushTime: null
      },
      isShow: true,
      excelHtml: '',
      wordHtml: '',
      excelData: [],
      dialog: {
        dialogVisible: false,
        src: '',
        isPdf: false,
        isExcel: false,
        isWord: false
      },
      loading: false
    };
  },
  watch: {
    $route(to, from) {
      location.reload();
    }
  },
  created() {
    this.getInfo(this.$route.query.id);
    this.beforeAndAfter(this.$route.query.id);
  },
  mounted() {},
  methods: {
    // 获取内容详情
    async getInfo(id) {
      const obj = {
        id
      };
      try {
        const result = await GetContentNoticeBYyId(obj);
        this.nameJudgment(result.data.typeName);
        this.content = result.data;
        document.getElementsByClassName('dynamicContent')[0].innerHTML = result.data.noticeText;
        this.isShow = !(this.content.typeName === '轮播页' || this.content.typeName === '轮播专题' || this.content.typeName === '头条');
      } catch (e) {
        console.log(e);
      }
    },
    returnList() {
      this.$router.push(this.fromPath)
    },
    // 判断数据类型
    nameJudgment(name) {
      switch (name) {
        case '现任领导':
          this.fromPath = '/depIntroduce'
          break;
        case '主要职能':
          this.fromPath = '/mainFunction'
          break;
        case '工作动态':
          this.fromPath = '/workTrend'
          break;
        case '时政要闻':
          this.fromPath = '/newsPolitical'
          break;
        case '信息公开':
          this.fromPath = '/inforBulletin'
          break;
        case '公示公告':
          this.fromPath = '/publicAnnouncement'
          break;
        case '部门预决算':
          this.fromPath = '/depBudgets'
          break;
        case '本地要闻':
          this.fromPath = '/newsCenter'
          break;
        case '基层统战':
          this.fromPath = '/basicUnitedFront'
          break;
        case '多党合作':
          this.fromPath = '/multiPartyCooperation'
          break;
        case '民族宗教':
          this.fromPath = '/nationalReligion'
          break;
        case '港澳台侨':
          this.fromPath = '/emigrant'
          break;
        case '非公经济':
          this.fromPath = '/nonePublicEconomy'
          break;
        case '党外知识分子和新的社会阶层':
          this.fromPath = '/newSocialClasses'
          break;
        case '学习新语':
          this.fromPath = '/learnNewTheory'
          break;
        case '理论园地':
          this.fromPath = '/theoreticalGarden'
          break;
        // case '机构设置':
        //   this.fromPath = '/mechanismSetup'
        //   break;
        // case '领导之窗':
        //   this.fromPath = '/windowOfLeadership'
        //   break;
        case '党的建设':
          this.fromPath = '/partyBuilding'
          break;
        case '学习贯彻党的二十届三中全会精神':
          this.fromPath = '/learnConferenceSpirit'
          break;
        default:
          break;
      }
    },
    // 获取上下条数据
    async beforeAndAfter(id) {
      if (!this.$route.query.type) {
        const result = await getContentUpDown(id);
        this.up = result.data.records[0];
        this.down = result.data.records[1];
      }
    },
    // 获取上条数据
    getBefore() {
      const obj = {
        id: this.up.id
      };
      this.$router.push({ path: '/article', query: obj });
    },

    // 获取下条数据
    getAfter() {
      const obj = {
        id: this.down.id
      };
      this.$router.push({ path: '/article', query: obj });
    },
    // 返回继续编辑
    editBack() {
      console.log(this.content);
      this.$store.commit('content/setContentInfo', this.content);
      this.$router.push({ path: '/contentRelease' });
      // this.$router.back()
    },
    // 返回列表页面
    listBack() {
      console.log(this.content);
      this.$store.commit('content/setContentInfo', null);
      // this.$router.push({ path: '/contentRelease' })
      this.$router.push({ path: '/contentAudit' });
    },
    // 提交
    async preToSubmit() {
      const obj = {
        id: this.$route.query.id
      };
      const result = await PublishContentNotice(obj);
      console.log('res', result);
      if (result.code === 200) {
        this.$router.go(0);
        this.$message({
          message: '提交成功！',
          type: 'success'
        });
      }
    },
    previewFile(content) {
      if (!(content.attachmentUrl.includes('.png') || content.attachmentUrl.includes('.jpg') || content.attachmentUrl.includes('.jpeg') || content.attachmentUrl.includes('.JPG') || content.attachmentUrl.includes('.PNG') || content.attachmentUrl.includes('.JPEG') || content.attachmentUrl.includes('.pdf') || content.attachmentUrl.includes('.xlsx') || content.attachmentUrl.includes('.xls') || content.attachmentUrl.includes('.doc') || content.attachmentUrl.includes('.docx'))) {
        this.$message.error('文件类型不支持预览')
        return false
      }
      if (content.attachmentUrl.includes('.pdf')) {
        this.dialog.isPdf = true
        this.dialog.isExcel = false
        this.dialog.isWord = false
        this.dialog.src = window.location.origin + '/api/' + content.attachmentUrl
      } else if (content.attachmentUrl.includes('.xls') || content.attachmentUrl.includes('.xlsx')) {
        this.dialog.isPdf = false
        this.dialog.isExcel = true
        this.dialog.isWord = false
        attachmentDownload(content.attachmentUrl).then(data => {
          const workbook = XLSX.read(new Uint8Array(data), { type: 'array' }) // 解析数据
          var worksheet = workbook.Sheets[workbook.SheetNames[0]] // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
          // this.excelHtml = XLSX.utils.sheet_to_html(worksheet) // 渲染成html
          const sheet2JSONOpts = {
            /** Default value for null/undefined values */
            defval: ''// 给defval赋值为空的字符串,不然没值的这列就不显示
          }
          // 渲染成json
          this.excelData = XLSX.utils.sheet_to_json(worksheet, sheet2JSONOpts)
          console.log(this.excelData)
        })
      } else if (content.attachmentUrl.includes('.doc') || content.attachmentUrl.includes('.docx')) {
        this.dialog.isPdf = false
        this.dialog.isExcel = false
        this.dialog.isWord = true
        this.dialog.src = window.location.origin + '/api/' + content.attachmentUrl
        // attachmentDownload(content.attachmentUrl).then(data => {
        //   mammoth.convertToHtml({ arrayBuffer: new Uint8Array(data) })
        //     .then(function(resultObject) {
        //       vm.$nextTick(() => {
        //         vm.wordHtml = resultObject.value
        //       })
        //     })
        // })
      } else if (content.attachmentUrl.includes('.jpg') || content.attachmentUrl.includes('.JPG') || content.attachmentUrl.includes('.jpeg') || content.attachmentUrl.includes('.png')) {
        this.dialog.isPdf = false
        this.dialog.isExcel = false
        this.dialog.isWord = false
        this.dialog.src = window.location.origin + '/api/' + content.attachmentUrl
      }
      this.dialog.dialogVisible = true
    },
    getHref(url, name) {
      attachmentDownload(url).then(res => {
        this.downloadBinaryFile(res, name) // 下载二进制文件
      })
    },
    downloadBinaryFile(binFile, fileName, blobType = 'application/octet-stream') {
      // 处理二进制数据并创建 Blob 对象
      const blobObj = new Blob([binFile], { type: blobType })
      // 创建一个链接并设置下载属性
      const downloadLink = document.createElement('a')
      let url = window.URL || window.webkitURL || window.moxURL // 兼容不同浏览器的 URL 对象
      url = url.createObjectURL(blobObj)
      downloadLink.href = url
      downloadLink.download = fileName // 设置下载的文件名
      // 将链接添加到 DOM 中，模拟点击
      document.body.appendChild(downloadLink)
      downloadLink.click()
      // 移除创建的链接和释放 URL 对象
      document.body.removeChild(downloadLink)
      window.URL.revokeObjectURL(url)
    }
  }
};
</script>

<!--<style lang="scss">-->
<style scoped lang="less">
@aaa: 192;
.workDynamic {
  font-family: 思源黑体 CN Medium;
  margin: 0 auto;
  width: (1660rem / @aaa);
  height: auto;
  .dynamicInner {
    width: (1660rem / @aaa);
    height: auto;
    margin: 0 auto;
    .dynamicInfo {
      width: 100%;
      height: auto;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      .dynamicTitle {
        width: 100%;
        height: auto;
        text-align: center;
        font-size: (40rem / @aaa);
        line-height: (50rem / @aaa);
        color: #254c8a;
        margin-bottom:( 15rem / @aaa);
      }
      .dynamicBrief {
        display: flex;
        flex-direction: row;
        justify-content: center;
        padding-bottom: (25rem / @aaa);
        border-bottom: #999999 (1rem /@aaa) dashed;
        font-family: 思源黑体 CN VF;
        font-weight: normal;
        .briefBox {
          margin-right: (24rem / @aaa);
          letter-spacing: (1rem / @aaa);
          font-size: (20rem / @aaa);
          color: #333333;
        }
      }
      .dynamicContent {
        margin-top: (20rem / @aaa);
        width: 100%;
        img {
          max-width: 100%;
        }
      }
      .attachment{
        display: flex;
        justify-content: flex-start;
        align-items: center;
        font-family: 思源黑体 CN VF;
        .word{
          //margin-top: (2rem / @aaa);
          font-size: (18rem / @aaa);
        }
        #el-button{
          font-size: (18rem / @aaa);
          margin-left: (30rem / @aaa);
        }
        #el-link{
          font-size: (18rem / @aaa);
        }
        .imgfile{

        }
      }
      .dynamicFooter {
        margin-top: (15rem / @aaa);
        margin-bottom: (66rem / @aaa);
        .pageJump {
          display: flex;
          flex-direction: column;
          //align-items: flex-start;
          //align-items: stretch;
          justify-content:space-around ;
          background-color:rgb(240, 245, 250) ;
          //background-color: #85ce61;
          height: (120rem / @aaa);
          //height: (102rem / @aaa);
          border-left: (4rem / @aaa) solid #024DA0;
          position: relative;
          // 正常样式
          .dynamicHref1 {
            height: (60rem / @aaa);
            width: (1460rem / @aaa);
            //height: (34rem / @aaa);
            position: relative;
            //width: 1000px;
            //white-space: nowrap;
            /* 文本不会换行 */
            //overflow: hidden;
            /* 隐藏超出元素宽度的内容 */
            //text-overflow: ellipsis;
            /* 显示省略符号来代表被修剪的文本 */
            a {
              position: absolute;
              top: 0;
              left: 0;
              margin-left: (21rem / @aaa);
              color: #254c8a;
              font-size: (30rem / @aaa);
              //font-size: (22rem / @aaa);
              line-height: (60rem / @aaa);
              //line-height: (34rem / @aaa);
              height: (60rem / @aaa);
              //height: (34rem / @aaa);
             /deep/ span{
               width: (1460rem / @aaa);
               //width: (1000rem / @aaa);
               white-space: nowrap;
               /* 文本不会换行 */
               overflow: hidden;
               /* 隐藏超出元素宽度的内容 */
               text-overflow: ellipsis;
               /* 显示省略符号来代表被修剪的文本 */
              }
              :hover {
                color: #4497f7;
              }
            }
          }
          // 禁用样式
          .dynamicHref2 {
            height: (60rem / @aaa);
            width: (1460rem / @aaa);
            position: relative;
            a {
              position: absolute;
              top: 0;

              margin-left: (21rem / @aaa);
              color: darkgrey;
              font-size:(30rem / @aaa);
              line-height: (60rem / @aaa);
              height: (60rem / @aaa);
              /deep/ span{
                width: (1460rem / @aaa);
                white-space: nowrap;
                /* 文本不会换行 */
                overflow: hidden;
                /* 隐藏超出元素宽度的内容 */
                text-overflow: ellipsis;
                /* 显示省略符号来代表被修剪的文本 */
              }
            }
          }
          .pageJump-right{
            height: (120rem / @aaa);
            //height: (102rem / @aaa);
            width: (120rem / @aaa);
            //width: (100rem / @aaa);
            background-color: #024DA0;
            position: absolute;
            right: 0;
            font-size: (30rem/@aaa);
            //字间距
            letter-spacing: (8rem /@aaa);
            text-align: center;
            color: #fff;
            line-height: (40rem /@aaa);
            //line-height: (26rem /@aaa);
            padding-top: (20rem/@aaa);
            padding-left: (12rem/@aaa);
            //padding: (20rem/@aaa);
          }
        }
        .subBtn {
          width: 100%;
          height: auto;
          text-align: center;
          margin-top: (15rem / @aaa);
          .el-button {
            width: (150rem / @aaa);
            height: (45rem / @aaa);
            font-size: (18rem / @aaa);
          }
        }
      }
    }
  }
}

[v-cloak] {
  display: none !important;
}
</style>
